/**
 WhereIsMyMail Copyright (c) 2012 Artem Kuroptev 

 This file is part of WhereIsMyMail. WhereIsMyMail is free software: you can redistribute it and/or modify it
 under the terms of the GNU General Public License as published by the Free Software Foundation,
 either version 3 of the License, or (at your option) any later version.

 WhereIsMyMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with WhereIsMyMail. If not, see <http://www.gnu.org/licenses/>.
 */

package com.ucware.wimm.pop3s;

import com.ucware.wimm.AbstractUp;

import javax.mail.*;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This tool intended to retrieve (and optionally expunge) all messages from INBOX folder on a POP3 server.
 * The tool is used with 'pop3s' JavaMail protocol, which is POP3 with SSL encription. <br>
 * <br>
 * Each retrieved message is stored in a current folder as a separate text file in MSG format.
 * Name of the file is composed from several fields of the message, like Date, From and Subject.<br>
 * <br>
 * See <a href="http://javamail.kenai.com/nonav/javadocs/com/sun/mail/pop3/package-summary.html">http://javamail.kenai.com/nonav/javadocs/com/sun/mail/pop3/package-summary.html</a><br>
 * See <a href="http://www.oracle.com/technetwork/java/sslnotes-150073.txt">http://www.oracle.com/technetwork/java/sslnotes-150073.txt</a><br>
 * <br>
 * 'Up' is from 'Update', as in SVN.<br>
 * <br>
 * $Id: Up.java 21 2012-12-05 15:20:43Z kuroptev@gmail.com $
 * <br>
 * @created 29.02.2012
 * @author Artem Kuroptev
 */
public class Up extends AbstractUp
{
    private static Logger log = Logger.getLogger(Up.class.getName());
    protected static void log(Object s) {log.info(s.toString());}
    protected static void log(Throwable s) {log.log(Level.SEVERE, s.getLocalizedMessage(), s);}

    public static void main(String[] args) throws MessagingException, IOException
    {
        setupLogManager();
        if(args.length < 1) {
            log("$Id: Up.java 21 2012-12-05 15:20:43Z kuroptev@gmail.com $");
            log("usage: java com.ucware.wimm.pop3s.Up <pop3s://user:password@host:port/INBOX> [expunge]");
            return;
        }

        try {
            final boolean deleteAndExpunge = args.length > 1 && args[1].equals("expunge");
            log("deleteAndExpunge: " + deleteAndExpunge);
            up(args[0], deleteAndExpunge);
        }
        catch (Exception e){
            log(e);
        }
    }

    public static void up(String url, boolean deleteAndExpunge) throws MessagingException, IOException {
        final Properties properties = new Properties(System.getProperties());
        up(url, deleteAndExpunge, properties);
    }

    public static void up(String url, boolean deleteAndExpunge, Properties properties) throws MessagingException, IOException
    {
        // Ignore server's cert path (allow self-signed) @@TODO move to calling CMD
        properties.put("mail.pop3s.ssl.trust", "*");
//      'mail.debug' property


        // The POP3 provider is accessed through the JavaMail APIs by using the protocol name "pop3"
        // or a URL of the form "pop3://user:password@host:port/INBOX".
        final Session session = Session.getInstance(properties,null);
        final Folder folder = session.getFolder(new URLName(url));
        try
        {
            log("Folder exist: "+folder.exists());

            log("Opening folder..");
            if(deleteAndExpunge) {
                folder.open(Folder.READ_WRITE);
            }
            else {
                folder.open(Folder.READ_ONLY);
            }

            final int count = folder.getMessageCount();
            log("folder.getMessageCount(): " + count);

            if(count > 0) {
                log("Reading messages..");
                final Message[] messages = folder.getMessages();
                log("Light-weight Message objects retrieved (getMessages): " + messages.length);

                exportMessages(messages);

                //  The expunge() method is not supported by the POP3 provider. Instead, after marking
                // the messages to be deleted by setting the DELETED flag on those messages,
                // close the folder with the expunge flag set to true. That is, invoke folder.close(true).
                if(deleteAndExpunge) {
                    log("Flagging messages as 'Deleted': " + messages.length);
                    for (int i = 0; i < messages.length; i++) {
                        final Message m = messages[i];
                        m.setFlag(Flags.Flag.DELETED, true);
                        log("Flagging 'Deleted': "+ (1+i)+"/"+messages.length+", " + m.getSentDate() +", " + m.getSubject());
                    }
                    log("folder.getMessageCount: " + folder.getMessageCount());
                }
            }
        }
        finally {
            log("Closing folder, deleteAndExpunge: " + deleteAndExpunge);
            folder.close(deleteAndExpunge); // close(expunge-delete-opt)
        }

        log("Reopening folder (for check)..");
        final Folder folder2 = session.getFolder(new URLName(url));
        try {
            folder2.open(Folder.READ_ONLY);
            log("folder2.getMessageCount: " + folder2.getMessageCount());
        }
        finally {
            log("Closing folder..");
            folder2.close(false); // close(expunge-delete-opt)
        }
        log("Done at: " + new Date());
    }
}
